let express = require('express');
let crypto = require('crypto');
let router = express.Router();
let cache = require('../../components/cache');

router.post('/', function (req, res, next) {
    let params = req.body;

    if (params.name === undefined || params.name === "") {
        res.json({"success": false, "message": "登录用户名不能为空！"});
        return;
    }

    if (params.password === undefined || params.password === "") {
        res.json({"success": false, "message": "密码不能为空！"});
        return;
    }

    req.app.db.query("select * from user where name = ?", [params.name], function (err, results) {
        if (err) {
            res.json({"success": false, "message": global.databaseErr, "detail": err});
            return;
        }

        if (results.length === 0) {
            res.json({"success": false, "message": "用户名不存在！"});
            return;
        }

        let user = results[0];

        if (user.password !== crypto.createHash("md5").update(params.password).digest('hex')) {
            req.session.destroy();
            res.clearCookie("user");
            res.clearCookie(global.cookieIndentity);delete req.session;
            res.json({"success": false, "message": "密码错误！"});
            return;
        }

        req.app.db.query("select * from role where id = ?", [user.roleId], function (err, results) {
            if (err) {
                res.json({"success": false, "message": global.databaseErr, "detail": err});
                return;
            }

            if (results.length === 0) {
                res.json({"success": false, "message": "用户角色信息错误！"});
                return;
            }

            let role = results[0];


            req.app.db.query("select id, fatherId, types, backName as name, backLink as cmp, smallImage as icon from menu where types > 0 and " + (req.headers.device === "mobile" ? "isMobile" : "isWeb") + " = ? order by `order` desc", [1], function (err, results) {
                if (err) {
                    res.json({"success": false, "message": global.databaseErr, "detail": err});
                    return;
                }

                if (results.length === 0) {
                    res.json({"success": false, "message": "当前用户没有可操作菜单！"});
                    return;
                }

                let menus = makeTree(results, 0);
                req.app.db.query("select name as text, value, keysValues as types, exception from dic order by keysValues, value", [], function (err, results, fields) {
                    if (err) {
                        res.json({"success": false, "message": global.databaseErr, "detail": err});
                        return;
                    }

                    let dics = {};
                    for (let i = 0; i < results.length; i++) {
                        if (dics[results[i].types] === undefined) {
                            dics[results[i].types] = []
                        }

                        dics[results[i].types].push(results[i]);
                    }

                    req.app.db.query("select id as value, name as text from department where fatherId = ?", [user.departmentId], function (err, results, fields) {
                        if (err) {
                            res.json({"success": false, "message": global.databaseErr, "detail": err});
                            return;
                        }

                        delete user.password;
                        cache.set(user.id, req.sessionID);
                        req.session.user = user;
                        req.session.role = role;

                        res.cookie("user", JSON.stringify({"id": user.id, "name": user.trueName}));
                        res.cookie("userId", user.id);
                        res.cookie("sessionId", req.sessionID);
                        res.json({"success": true, "data": {"user": user, "menu": menus, "dics": dics, "sonDepartments": results}, "message": "登录成功！"});
                    });

                });
            });
        });
    });
});


function makeTree(data, fatherId) {
    let datas = [];
    for (var i = 0; i < data.length; i ++) {
        if (data[i].fatherId === fatherId) {
            data[i].items = makeTree(data, data[i].id);
            datas.push(data[i]);
        }
    }
    return datas;
}

module.exports = router;